<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>ajax请求超时和取消请求</h1>
    <button class="btn1">点击我发送get方法的ajax</button>
    <button class="btn2">点击发送get形式的ajax按钮二</button>
    <button class="btn3">点击我取消上一个ajax</button>

    <script>

     let btn1 =document.querySelector(".btn1");
     let btn2 =document.querySelector(".btn2");
     let btn3 =document.querySelector(".btn3");

     btn1.onclick = function () {
         let xhr = new XMLHttpRequest();
         xhr.open("get","/getdata");
         xhr.timeout=2000;

         xhr.onload =function(){
            if(xhr.status>=200 && xhr.status<300){
                    console.log(xhr.responseText);
                }
         }
         xhr.ontimeout= function(){
             alert("请求超时")
         }
         xhr.send();
     };

     let xhr2;


     btn2.onclick = function () {
        if(typeof xhr2 !== "undefined"){ //防止手抖不断点击请求
                // 证明xhr被赋值了，开启了一个ajax
                xhr2.abort(); // 取消
            }

         xhr2 =new XMLHttpRequest()
         xhr2.open("get","/getdata");
         xhr2.send();
         xhr2.onload= function () {
            if(xhr2.status>=200 && xhr2.status<300){
                    console.log(xhr.responseText,'xhr2');
                }
             
         }
     }

     btn3.onclick = function () {
         xhr2.onabort = function () {
            // alert("取消了");
         }
         xhr2.abort();
     }
    </script>
</body>
</html>